package com.example.musicaiap.data.repository

import com.example.musicaiap.domain.model.Playlist
import com.example.musicaiap.domain.model.Song
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import java.util.UUID
import javax.inject.Inject
import javax.inject.Singleton
import android.util.Log

/**
 * 音乐仓库的模拟实现
 * 用于开发测试阶段，提供假数据
 */
@Singleton
class FakeMusicRepository @Inject constructor() : MusicRepository {
    
    private val TAG = "FakeMusicRepository"
    
    // 模拟收藏歌曲列表
    private val favoriteSongIds = MutableStateFlow<Set<String>>(emptySet())
    
    // 存储本地扫描到的歌曲
    private val localSongs = mutableListOf<Song>()
    
    // 模拟歌曲数据
    private val songs = listOf(
        Song(
            id = "song1",
            title = "Mojito",
            artist = "周杰伦",
            album = "最伟大的作品",
            duration = 250000L,
            coverUrl = "https://p2.music.126.net/9MjV-NrZ-uksX1k-2jbkow==/109951165033861023.jpg",
            url = "https://example.com/song1.mp3"
        ),
        Song(
            id = "song2",
            title = "不知道",
            artist = "周兴哲",
            album = "如果雨之后",
            duration = 244000L,
            coverUrl = "https://p2.music.126.net/v_zCe1KvuW_2ssDgCOw-Hg==/109951165395883156.jpg",
            url = "https://example.com/song2.mp3"
        ),
        Song(
            id = "song3",
            title = "Dynamite",
            artist = "BTS",
            album = "BE",
            duration = 240000L,
            coverUrl = "https://p2.music.126.net/rJYz9YqJ-iKiMTMw2tSdwQ==/109951165352180895.jpg",
            url = "https://example.com/song3.mp3"
        ),
        Song(
            id = "song4",
            title = "起风了",
            artist = "买辣椒也用券",
            album = "起风了",
            duration = 325000L,
            coverUrl = "https://p1.music.126.net/diGAyEmpymX8G7JcnElncQ==/109951163699673355.jpg",
            url = "https://example.com/song4.mp3"
        ),
        Song(
            id = "song5",
            title = "Blinding Lights",
            artist = "The Weeknd",
            album = "After Hours",
            duration = 200000L,
            coverUrl = "https://p2.music.126.net/F-5o0ek44l02R5CkVzXZ8g==/109951165031509430.jpg",
            url = "https://example.com/song5.mp3"
        )
    )
    
    // 模拟播放列表数据
    private val playlists = listOf(
        Playlist(
            id = "playlist1",
            name = "流行热歌",
            description = "最热门的流行歌曲，每日更新",
            coverUrl = "https://p1.music.126.net/PCYs2vq58cJ7DiGvQdHn3Q==/109951167295248390.jpg",
            songCount = 50,
            isOfficial = true
        ),
        Playlist(
            id = "playlist2",
            name = "经典老歌",
            description = "那些年，我们一起听过的歌",
            coverUrl = "https://p1.music.126.net/O8LkkfC7PtV2xwp8w_TLdw==/109951164061382394.jpg",
            songCount = 100,
            isOfficial = true
        ),
        Playlist(
            id = "playlist3",
            name = "华语说唱",
            description = "最热门的中文说唱歌曲",
            coverUrl = "https://p1.music.126.net/mS2ZkGExH2R_22n-Qwpk8A==/109951164432303700.jpg",
            songCount = 30,
            isOfficial = false
        ),
        Playlist(
            id = "playlist4",
            name = "我的私享歌单",
            description = "根据您的听歌习惯生成",
            coverUrl = "https://p2.music.126.net/0-Ybpa8FrDfRgKYCTJD8Xg==/109951164796381543.jpg",
            songCount = 25,
            isOfficial = false
        ),
        Playlist(
            id = "playlist5",
            name = "欧美热歌",
            description = "最新最热的欧美流行音乐",
            coverUrl = "https://p2.music.126.net/QxJA2mr4hhb9DZyucIOIxw==/109951165422200291.jpg",
            songCount = 45,
            isOfficial = true
        )
    )
    
    // 模拟播放列表歌曲映射
    private val playlistSongs = mapOf(
        "playlist1" to listOf("song1", "song2", "song4"),
        "playlist2" to listOf("song3", "song5"),
        "playlist3" to listOf("song1", "song3", "song4"),
        "playlist4" to listOf("song2", "song5"),
        "playlist5" to listOf("song3", "song5")
    )
    
    override suspend fun getRecommendSongs(): List<Song> {
        // 模拟推荐歌曲，随机排序
        return songs.shuffled().take(3)
    }
    
    override suspend fun getPlaylists(): List<Playlist> {
        return playlists
    }
    
    override suspend fun getPlaylist(playlistId: String): Playlist {
        return playlists.find { it.id == playlistId }
            ?: throw IllegalArgumentException("Playlist not found with id: $playlistId")
    }
    
    override suspend fun getPlaylistSongs(playlistId: String): List<Song> {
        val songIds = playlistSongs[playlistId] ?: return emptyList()
        return songs.filter { it.id in songIds }
    }
    
    override suspend fun getSong(songId: String): Song {
        // 先检查是否为本地歌曲
        val localSong = localSongs.find { it.id == songId }
        if (localSong != null) {
            return localSong
        }
        
        // 再检查预设歌曲
        return songs.find { it.id == songId }
            ?: throw IllegalArgumentException("Song not found with id: $songId")
    }
    
    override fun getSongById(songId: String): Song? {
        Log.d(TAG, "查询歌曲ID: $songId")
        
        // 先检查是否为本地歌曲
        val localSong = localSongs.find { it.id == songId }
        if (localSong != null) {
            Log.d(TAG, "在本地歌曲中找到: ${localSong.title}")
            return localSong
        }
        
        // 再检查预设歌曲
        val song = songs.find { it.id == songId }
        if (song != null) {
            Log.d(TAG, "在预设歌曲中找到: ${song.title}")
            return song
        }
        
        Log.d(TAG, "未找到歌曲: $songId")
        return null
    }
    
    override fun getSongsByPlaylistId(playlistId: String): List<Song> {
        val songIds = playlistSongs[playlistId] ?: return emptyList()
        return songs.filter { it.id in songIds }
    }
    
    override suspend fun searchSongs(query: String): List<Song> {
        return if (query.isBlank()) {
            emptyList()
        } else {
            songs.filter {
                it.title.contains(query, ignoreCase = true) ||
                it.artist.contains(query, ignoreCase = true) ||
                it.album.contains(query, ignoreCase = true)
            }
        }
    }
    
    override suspend fun getLyrics(songId: String): String? {
        // 模拟歌词，简单返回
        return when (songId) {
            "song1" -> "[00:00.00]Mojito - 周杰伦\n[00:04.00]词：方文山\n[00:08.00]曲：周杰伦\n..."
            "song2" -> "[00:00.00]不知道 - 周兴哲\n[00:04.00]词：小寒\n[00:08.00]曲：周兴哲\n..."
            else -> null
        }
    }
    
    override suspend fun addToFavorites(songId: String) {
        Log.d(TAG, "添加歌曲到收藏: $songId")
        favoriteSongIds.update { it + songId }
        Log.d(TAG, "当前收藏列表: ${favoriteSongIds.value}")
    }
    
    override suspend fun removeFromFavorites(songId: String) {
        Log.d(TAG, "从收藏中移除歌曲: $songId")
        favoriteSongIds.update { it - songId }
        Log.d(TAG, "当前收藏列表: ${favoriteSongIds.value}")
    }
    
    override suspend fun isSongFavorite(songId: String): Boolean {
        Log.d(TAG, "检查歌曲收藏状态: $songId")
        val exactMatch = songId in favoriteSongIds.value
        Log.d(TAG, "歌曲 $songId 收藏状态: $exactMatch, 当前收藏列表: ${favoriteSongIds.value}")
        return exactMatch
    }
    
    override suspend fun toggleFavorite(songId: String): Boolean {
        Log.d(TAG, "切换歌曲收藏状态: $songId")
        val isFavorite = !isSongFavorite(songId)
        if (isFavorite) {
            addToFavorites(songId)
        } else {
            removeFromFavorites(songId)
        }
        Log.d(TAG, "歌曲 $songId 收藏状态更改为: $isFavorite, 当前收藏列表: ${favoriteSongIds.value}")
        return isFavorite
    }
    
    override fun getFavoriteSongs(): Flow<List<Song>> {
        return favoriteSongIds.asStateFlow().map { ids ->
            Log.d(TAG, "获取收藏歌曲列表, 收藏ID数量: ${ids.size}, IDs: $ids")
            
            // 从预设歌曲中查找收藏的歌曲
            val favoriteSongs = songs.filter { it.id in ids }
            Log.d(TAG, "从预设歌曲中找到收藏歌曲: ${favoriteSongs.size}首")
            
            // 从本地歌曲中查找收藏的歌曲
            val favoriteLocalSongs = localSongs.filter { it.id in ids }
            Log.d(TAG, "从本地歌曲中找到收藏歌曲: ${favoriteLocalSongs.size}首")
            
            // 合并两个列表
            val allFavoriteSongs = favoriteSongs + favoriteLocalSongs
            Log.d(TAG, "合并后的收藏歌曲总数: ${allFavoriteSongs.size}首")
            
            allFavoriteSongs
        }
    }

    /**
     * 保存本地扫描到的歌曲列表
     * @param scannedSongs 扫描到的歌曲列表
     */
    fun saveLocalSongs(scannedSongs: List<Song>) {
        Log.d(TAG, "保存本地歌曲 ${scannedSongs.size} 首")
        localSongs.clear()
        localSongs.addAll(scannedSongs)
    }
} 